import axios from 'axios';
import qs from 'qs';

// //设置根目录url
// axios.defaults.;
// //设置post的头部参数
// axios.defaults.headers.post['Content-Type'] = '';
// //设置超时时间
// axios.defaults.timeout = 5000 ;


var service=axios.create({
    timeout:5000,
    baseURL : 'http://admin.slf0319.com/api',
    headers:{
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
})
//设置axios的拦截器，在每次使用axios的post方法请求之前对参数进行序列化
service.interceptors.request.use((config)=>{
    if(config.method == 'post'){

        config.data = qs.stringify(config.data);
    }
    return config;
},(error)=>{
    return Promise.reject(error).catch(error => console.log('caught', error.message));
});

//服务器返回数据之后，设置拦截器拦截
service.interceptors.response.use((res)=>{
    console.log(123123);

    var data = res.data,
    code = ('ret' in data) ? data.ret : 200 ;
    if(code == 400 || code < 0){
        //请求失败
        return Promise.resolve(res).catch(error => console.log('caught', error.message));
    }

    return res;
});

export function post(url,params){
    return new Promise((resolve, reject) => {
        service.post(url, params)
        .then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    }).catch(error => console.log('caught', error.message))
}
export function postUpload(params){
    return new Promise((resolve, reject) => {
        service.post('http://upload.qiniu.com/', params)
        .then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    }).catch(error => console.log('caught', error.message))

}

export function get(url,params){
    return new Promise((resolve, reject) => {

        service.get(url, {params})
        .then(response => {
            resolve(response.data);
        }, err => {
            reject(err);
        })
        .catch((error) => {
            reject(error)
        })
    }).catch(error => console.log('caught', error.message))

}
